package com.lanhao.aot.pdfmerge;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.core.img.ImgUtil;

/**
 * PDF转换成图片工具类
 * 
 * @author Administrator
 *
 */
public class PDF2ImageUtil {
	private static final Logger LOG = LoggerFactory.getLogger(PDF2ImageUtil.class);
	public static BufferedImage cdekTemplateImage = null;
	public static BufferedImage ruTemplateImage = null;
	public static BufferedImage ruDiyTemplateImage = null;
	
	static {
		try {
			cdekTemplateImage = ImgUtil.read(new URL("https://res-oss.anhelogistics.com/image/CEDKTemplate.png"));
			ruTemplateImage = ImgUtil.read(new URL("https://res-oss.anhelogistics.com/image/RussianPostTemplate.png"));
			ruDiyTemplateImage = ImgUtil.read(new URL("https://res-oss.anhelogistics.com/image/RussianPostDiyTemplate.png"));
			LOG.info("加载远程CDEK的模板图片成功, 宽度:{}, 高度:{}", cdekTemplateImage.getWidth(), cdekTemplateImage.getHeight());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static List<BufferedImage> pdf2BufferedImageList(File filePath) {
		try (PDDocument doc = PDDocument.load(filePath);) {
			return pdf2BufferedImageList(doc);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static List<BufferedImage> pdf2BufferedImageList(InputStream is) {
		try (PDDocument doc = PDDocument.load(is);) {
			return pdf2BufferedImageList(doc);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static List<BufferedImage> pdf2BufferedImageList(PDDocument doc) throws IOException {
		// 在此处处理，将标签转为图片后追加说明页面
		ArrayList<BufferedImage> imageList = new ArrayList<BufferedImage>();
		int numberOfPages = doc.getNumberOfPages();
		PDFRenderer renderer = new PDFRenderer(doc);
		for (int i = 0; i < numberOfPages; i++) {
			// 页码，从0开始；scale 1 = 72DPI，值越大像素越高；图片类型
			BufferedImage labelImage = renderer.renderImage(i, 2, ImageType.RGB);
			imageList.add(labelImage);
		}
		return imageList;
	}
	
	public static BufferedImage pdf2Image(File sourceFile, File destFile) throws IOException {
		try (PDDocument doc = PDDocument.load(sourceFile);) {
			// 在此处处理，将标签转为图片后追加说明页面
			int numberOfPages = doc.getNumberOfPages();
			PDFRenderer renderer = new PDFRenderer(doc);
			for (int i = 0; i < numberOfPages;) {
				// 页码，从0开始；scale 1 = 72DPI，值越大像素越高；图片类型
				BufferedImage labelImage = renderer.renderImage(i, 2, ImageType.RGB);
				if (destFile != null) {
					ImageIO.write(labelImage, FilenameUtils.getExtension(destFile.getName()), destFile);
				}
				return labelImage;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 合并多张图片
	 * 
	 * @param path
	 * @param picList
	 * @param suffix
	 * @param mergeType
	 */
	public static void mergeImagetogeter(File destFile, List<BufferedImage> picList, String suffix, String mergeType) {
		try {
			Pair<Integer,Integer> needWithAndHeight = getNeedWithAndHeight(picList, mergeType);
			BufferedImage newImage = new BufferedImage(needWithAndHeight.getLeft(), needWithAndHeight.getRight(), BufferedImage.TYPE_INT_RGB);
			Graphics g = newImage.getGraphics();
			int x = 0;
			int y = 0;
			for (int i = 0; i < picList.size(); i++) {
				BufferedImage currentImage = picList.get(i);
				int cwidth = currentImage.getWidth();
				int cheight = currentImage.getHeight();
				g.drawImage(currentImage, x, y, cwidth, cheight, null);
				if ("0".equals(mergeType)) {
					x += cwidth;
				} else {
					y += cheight;
				}
			}
			ImageIO.write(newImage, suffix, new FileOutputStream(destFile));
			g.dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据合并方式
	 * @param picList
	 * @param mergeType
	 * @return
	 */
	public static Pair<Integer, Integer> getNeedWithAndHeight(List<BufferedImage> picList, String mergeType) {
		BufferedImage firstImage = picList.get(0);
		int w1 = firstImage.getWidth();
		int h1 = firstImage.getHeight();
		int width = 0;
		int height = 0;
		for (int i = 0; i < picList.size(); i++) {
			BufferedImage currentImage = picList.get(i);
			int cwidth = currentImage.getWidth();
			int cheight = currentImage.getHeight();
			// 横着合并
			if ("0".equals(mergeType)) {
				width += cwidth;
				height = h1;
			} else {
				width = w1;
				height += cheight;
			}
		}
		LOG.info("最终需要的宽度和高度为width={}, height={}", width, height);
		return Pair.of(width, height);
	}
}
